local pp = require("lib.preprocess")
local lfs = require ("lfs")
local lume = require("lib.lume")

local DBG = false
local INIT_PP_DIR = "pp"

local pp_opts = {
   addLineNumbers = false,
   jitSyntax = true,
   release = false,
   debug = false,
   backtickStrings = true,
}

local get_dir_files = function(path)
   local file_list = {}
   for file in lfs.dir(path) do
      if file ~= "." and file ~= ".."then
	 local f = path.."/"..file
	 local attr = lfs.attributes(f)
	 assert(type(attr) == "table")
	 if attr.mode == "file" then
	    local ext = string.match(file, "%w+%.(%w+)")
	    if ext == "lua2p" then
	       lume.push(file_list, f)
	    end
	 end
      end
   end
   return file_list
end


local function preprocess_files (...)
   lume.each({...},
      function (path)
	 local out = string.gsub(path, "(%.lua2p)", ".lua")
	 out = string.gsub(out, "(/lua2p/)", "/gen/")
	 local name = string.match(out, "/(%w+%.lua)")
	 if DBG then
	    print(path.." -> "..out)
	 end
	 lume.extend(pp_opts, {pathIn=path, pathOut=out, pathMeta = out..".temp"})
	 local info, err = pp.processFile(pp_opts)
	 if not info then  os.exit(1)  end
   end)
end

local function preprocess_dirs (...)
   local paths = {}
   lume.each({...}, function (path)
	 lume.each(get_dir_files(path), function (v)
		      lume.push(paths, v)
	 end)
   end)
   preprocess_files(unpack(paths))
end

preprocess_dirs(INIT_PP_DIR)

return { preprocess_dirs = preprocess_dirs,
	 preprocess_file = preprocess_file,
	 preprocess_files = preprocess_files }
